const nunjucks = require('nunjucks')

function createEvn(path, opts){
  var  autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false;
  console.log(new nunjucks.FileSystemLoader(path,{
    noCache: noCache,
    watch: watch
  }))
  const env = new nunjucks.Environment(
      new nunjucks.FileSystemLoader(path,{
        noCache: noCache,
        watch: watch
      }),
      {
        autoescape: autoescape,
        throwOnUndefined: throwOnUndefined
      }
  )

  if(opts.filters){
    for(let f in opts.filters){
      env.addFilter(f, opts.filters[f])
    }
  }
  return env
}

function renterTempalte(path, opts) {
  const env = createEvn(path, opts)
  return async(ctx,next) => {
    ctx.render = function(fileName, model){
        ctx.response.body = env.render(fileName,Object.assign({}, ctx.state || {}, model || {}))
        ctx.response.type = "text/html"
    }
    await next()
  }
}

module.exports = renterTempalte;